import 'package:audio_session/audio_session.dart';
import 'package:flutter_sound/public/flutter_sound_player.dart';
import 'package:logger/logger.dart' show Level, Logger;
import 'package:my_app/base/foundation/jd_file_tool.dart';
import 'package:my_app/base/utils/jd_log.dart';

typedef TDPlayCallback = void Function(
    bool isPlaying, String playPath, double currentPlaySecond);

//音频播放单例
class VoicePlayerInstance {
  factory VoicePlayerInstance() => _instance;
  static final VoicePlayerInstance _instance = VoicePlayerInstance._internal();

  VoicePlayerInstance._internal();

  bool audioBaseConfiged = false;

  setUpPlayerConfig() async {
    if (audioBaseConfiged) {
      return;
    }
    //设置音频
    final session = await AudioSession.instance;
    await session.configure(AudioSessionConfiguration(
      avAudioSessionCategory: AVAudioSessionCategory.playAndRecord,
      avAudioSessionCategoryOptions:
          AVAudioSessionCategoryOptions.allowBluetooth |
              AVAudioSessionCategoryOptions.defaultToSpeaker,
      avAudioSessionMode: AVAudioSessionMode.spokenAudio,
      avAudioSessionRouteSharingPolicy:
          AVAudioSessionRouteSharingPolicy.defaultPolicy,
      avAudioSessionSetActiveOptions: AVAudioSessionSetActiveOptions.none,
      androidAudioAttributes: const AndroidAudioAttributes(
        contentType: AndroidAudioContentType.speech,
        flags: AndroidAudioFlags.none,
        usage: AndroidAudioUsage.voiceCommunication,
      ),
      androidAudioFocusGainType: AndroidAudioFocusGainType.gain,
      androidWillPauseWhenDucked: true,
    ));
    audioBaseConfiged = true;
  }

  TDPlayCallback? voicePlayerCallback;
  FlutterSoundPlayer voicePlayer = FlutterSoundPlayer(logLevel: Level.error);
  // FlutterSoundPlayer voicePlayer = FlutterSoundPlayer();
  PlayerState get playerState => voicePlayer.playerState;

  bool get isPlaying {
    return playerState == PlayerState.isPlaying;
  }

  String currentPlayPath = '';
  double currentPlaySecond = 0;

  void startPlay(String path,
      {Function(bool isPlaying, String playPath, double currentPlaySecond)?
          callBack}) async {
    if (voicePlayer.isPaused &&
        currentPlayPath.isNotEmpty &&
        currentPlayPath == path) {
      voicePlayerCallback = callBack;
      voicePlayerCallback?.call(true, currentPlayPath, currentPlaySecond);
      resumePlayer();
      return;
    }
    await _setUp();
    voicePlayerCallback = callBack;
    currentPlayPath = path;
    try {
      if (path.contains('http')) {
        await voicePlayer.startPlayer(
            fromURI: path,
            // codec: Codec.mp3,
            sampleRate: 44000,
            whenFinished: () {
              jdLog("播放完成----->");
              voicePlayerCallback?.call(
                  false, currentPlayPath, currentPlaySecond);
            });
      } else {
        //判断文件是否存在
        if (await JDFileTool.fileExists(path)) {
          jdLog("开始播放----->");
          await voicePlayer.startPlayer(
              fromURI: path,
              sampleRate: 44000,
              whenFinished: () {
                jdLog("播放完成----->");
                voicePlayerCallback?.call(
                    false, currentPlayPath, currentPlaySecond);
              });
        } else {
          jdLog("文件不存在----->");
          voicePlayerCallback?.call(false, currentPlayPath, currentPlaySecond);
          return;
        }
      }
      //监听播放进度
      voicePlayer.onProgress!.listen((PlaybackDisposition e) {
        DateTime date = DateTime.fromMillisecondsSinceEpoch(
            e.position.inMilliseconds,
            isUtc: true);
        jdLog("播放进度----->  ${date.second}");
        currentPlaySecond = date.second.toDouble();
        voicePlayerCallback?.call(true, currentPlayPath, currentPlaySecond);
      });
    } catch (err) {
      voicePlayerCallback?.call(false, currentPlayPath, currentPlaySecond);
    }
  }

  pausePlayer(bool cleanCallBack) async {
    if (voicePlayer.isPlaying) {
      await voicePlayer.pausePlayer();
      voicePlayerCallback?.call(false, currentPlayPath, currentPlaySecond);
      if (cleanCallBack) {
        voicePlayerCallback = null;
        currentPlayPath = '';
        currentPlaySecond = 0;
      }
    }
  }

  resumePlayer() async {
    if (voicePlayer.isPaused) {
      await voicePlayer.resumePlayer();
      voicePlayerCallback?.call(true, currentPlayPath, currentPlaySecond);
    }
  }

  /// 杀死播放器
  // Future<void> stopPlay() async {
  //   if (voicePlayer.isPlaying) {
  //     await voicePlayer.stopPlayer();
  //     voicePlayerCallback?.call(false, currentPlayPath);
  //     voicePlayerCallback = null;
  //     currentPlayPath = '';
  //   }
  // }

  _setUp() async {
    if (!VoicePlayerInstance().voicePlayer.isOpen()) {
      jdLog("初始化播放器----");
      await VoicePlayerInstance().voicePlayer.openPlayer();
      //设置1s回调一次
      await VoicePlayerInstance()
          .voicePlayer
          .setSubscriptionDuration(const Duration(milliseconds: 1000));
    }
    await setUpPlayerConfig();
    await pausePlayer(true);
  }

  ///获取播放状态
  Future<PlayerState> getPlayState() async {
    return await voicePlayer.getPlayerState();
  }
}
